package handlers

import (
	"restaurant-system/config"
	"restaurant-system/internal/models"

	"github.com/gin-gonic/gin"
)

// 添加到购物车请求
type AddToCartRequest struct {
	DishID   uint    `json:"dish_id" binding:"required"`
	Quantity int     `json:"quantity" binding:"required,min=1"`
	Price    float64 `json:"price" binding:"required,gt=0"`
}

// 添加到购物车
func AddToCart(c *gin.Context) {
	userID, _ := c.Get("userID")
	var req AddToCartRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	// 检查菜品是否存在
	var dish models.Dish
	if err := config.DB.First(&dish, req.DishID).Error; err != nil {
		c.JSON(404, gin.H{"error": "菜品不存在"})
		return
	}

	// 检查库存
	if dish.Stock < req.Quantity {
		c.JSON(400, gin.H{"error": "库存不足"})
		return
	}

	// 检查是否已在购物车中
	var existingItem models.CartItem
	result := config.DB.Where("user_id = ? AND dish_id = ?", userID, req.DishID).First(&existingItem)
	if result.Error == nil {
		// 更新数量
		newQuantity := existingItem.Quantity + req.Quantity
		if dish.Stock < newQuantity {
			c.JSON(400, gin.H{"error": "库存不足"})
			return
		}

		if err := config.DB.Model(&existingItem).Update("quantity", newQuantity).Error; err != nil {
			c.JSON(500, gin.H{"error": "更新购物车失败"})
			return
		}

		c.JSON(200, gin.H{"message": "更新购物车成功", "item": existingItem})
		return
	}

	// 创建新购物车项
	cartItem := models.CartItem{
		UserID:   userID.(uint),
		DishID:   req.DishID,
		Quantity: req.Quantity,
		Price:    req.Price,
		Selected: true,
	}

	if err := config.DB.Create(&cartItem).Error; err != nil {
		c.JSON(500, gin.H{"error": "添加到购物车失败"})
		return
	}

	c.JSON(200, gin.H{"message": "添加到购物车成功", "item": cartItem})
}

// 更新购物车请求
type UpdateCartRequest struct {
	Quantity int  `json:"quantity" binding:"required,min=0"`
	Selected bool `json:"selected"`
}

// 更新购物车
func UpdateCart(c *gin.Context) {
	userID, _ := c.Get("userID")
	itemID := c.Param("id")
	var req UpdateCartRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	// 检查购物车项是否存在
	var cartItem models.CartItem
	if err := config.DB.Where("id = ? AND user_id = ?", itemID, userID).First(&cartItem).Error; err != nil {
		c.JSON(404, gin.H{"error": "购物车项不存在"})
		return
	}

	if req.Quantity > 0 {
		// 检查库存
		var dish models.Dish
		if err := config.DB.First(&dish, cartItem.DishID).Error; err != nil {
			c.JSON(404, gin.H{"error": "菜品不存在"})
			return
		}

		if dish.Stock < req.Quantity {
			c.JSON(400, gin.H{"error": "库存不足"})
			return
		}

		cartItem.Quantity = req.Quantity
	}
	cartItem.Selected = req.Selected

	if err := config.DB.Save(&cartItem).Error; err != nil {
		c.JSON(500, gin.H{"error": "更新购物车失败"})
		return
	}

	c.JSON(200, gin.H{"message": "更新购物车成功", "item": cartItem})
}

// 删除购物车项
func DeleteCartItem(c *gin.Context) {
	userID, _ := c.Get("userID")
	itemID := c.Param("id")

	result := config.DB.Where("id = ? AND user_id = ?", itemID, userID).Delete(&models.CartItem{})
	if result.RowsAffected == 0 {
		c.JSON(404, gin.H{"error": "购物车项不存在"})
		return
	}

	c.JSON(200, gin.H{"message": "删除成功"})
}

// 获取购物车列表
func GetCart(c *gin.Context) {
	userID, _ := c.Get("userID")
	var cartItems []models.CartItem

	if err := config.DB.Preload("Dish").Where("user_id = ?", userID).Find(&cartItems).Error; err != nil {
		c.JSON(500, gin.H{"error": "获取购物车失败"})
		return
	}

	// 计算总价
	var totalPrice float64
	var selectedPrice float64
	for _, item := range cartItems {
		if item.Selected {
			selectedPrice += item.Price * float64(item.Quantity)
		}
		totalPrice += item.Price * float64(item.Quantity)
	}

	c.JSON(200, gin.H{
		"items":          cartItems,
		"total_price":    totalPrice,
		"selected_price": selectedPrice,
	})
}

// 清空购物车
func ClearCart(c *gin.Context) {
	userID, _ := c.Get("userID")

	if err := config.DB.Where("user_id = ?", userID).Delete(&models.CartItem{}).Error; err != nil {
		c.JSON(500, gin.H{"error": "清空购物车失败"})
		return
	}

	c.JSON(200, gin.H{"message": "清空购物车成功"})
}
